
import { GetLocation, GetState, ListDevicesOfLocation, ListLocations, UpdateDevice } from "~/lib/server";
import type { Route } from "./+types/location";
import invariant from "tiny-invariant";
import { ActionButton, Button, ButtonGroup, Content, Dialog, DialogContainer, DialogTrigger, Divider, Form, Heading, TextField, useDialogContainer, View } from '@adobe/react-spectrum';
import { useEffect, useState } from "react";
import { DestroyLocation } from "./location/delete";
import { EditLocation } from "./location/edit";
// import { EditDevice } from "./device/edit";
import { DeviceCommand, DeviceState } from "~/ui/device";

import {
    useQuery,
} from '@tanstack/react-query'
import { fetcher } from "~/lib/fetcher";
import { useActionData, useFetcher, type LoaderFunctionArgs } from "react-router";
import { SelectLocation } from "~/ui/select-location";



export default function Location({ params }: Route.ComponentProps) {

    const { data: location, error: locationErr, isLoading: locationIsLoading } = GetLocation(params.locationId);
    const { data: devices, error: devicesErr, isLoading: devicesIsLoading } = ListDevicesOfLocation(params.locationId);

    return (
        <>
            {location &&

                <div>
                    <h2 className="my-2 text-3xl">{location.name}</h2>

                    {location.id > 0 &&
                        <div className="my-2 flex gap-2">

                            <EditLocation location={location} />

                            <DestroyLocation location={location} />

                        </div>
                    }
                </div>
            }

            {devices?.length ?
                <div className="flex flex-col sm:flex-row gap-4" >

                    {devices.map((item) => (
                        <DeviceCard device={item} key={item.id} />
                    ))}

                </div>
                : ""
            }
        </>
    );



}



function DeviceCard({ device }: { device: Device }) {


    let [dialog, setDialog] = useState(false);
    let [editDialog, setEditDialog] = useState(false);


    let disabled = false;

    switch (device.type) {
        case 19:
            disabled = true;
    }






    return (
        <>
            <div className=" flex flex-col">

                <ActionButton isQuiet onPress={() => setEditDialog(true)}>
                    <span className="text-xl mb-2">{device.name}</span>
                </ActionButton>






                <button className="w-36 bg-white shadow-md rounded-lg px-4 py-2" disabled={disabled}
                    onClick={() => setDialog(true)}
                >

                    {/* <svg className="w-6 h-6 mr-2"></svg> */}

                    <p className="text-gray-700 text-base">{device.type}</p>
                    <div className="text-gray-700 text-base">
                        <DeviceState device={device} />
                    </div>


                </button >

            </div>


            <DialogContainer onDismiss={() => setDialog(false)} isDismissable>
                {dialog && <DeviceCommandDialog device={device} />}
            </DialogContainer>
            <DialogContainer onDismiss={() => setEditDialog(false)} isDismissable>
                {editDialog && <DeviceEditDialog device={device} />}
            </DialogContainer>

        </>
    )
}


function DeviceCommandDialog({ device }: { device: Pick<Device, "name" | "guid" | "type"> }) {

    return (

        <Dialog >
            <Heading>{device.name}</Heading>
            <Divider></Divider>
            <Content>
                <DeviceCommand device={device} />
            </Content>
        </Dialog >

    );
}

function DeviceEditDialog({ device }: { device: Pick<Device, "name" | "locationId" | "id"> }) {

    let dialog = useDialogContainer();

    let onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        // Prevent default browser page refresh.
        e.preventDefault();

        // Get form data as an object.
        const formData = new FormData(e.currentTarget);


        const data = {
            name: formData.get("name"),
            locationId: +(formData.get("locationId") || 0),
        };
        // Submit to your backend API...

        try {
            UpdateDevice(device.id, data);
            dialog.dismiss();
        } catch (error) {
            return { error: "error" }
        }
    };


    return (


        <Dialog >
            <Heading>{device.name}</Heading>
            <Divider></Divider>
            <Content>
                <Form onSubmit={onSubmit}>
                    <TextField name="name" label="设备名称" defaultValue={device.name} />
                    <SelectLocation defaultSelectedKey={device.locationId}></SelectLocation>
                    <Button variant="accent" type="submit">修改</Button>
                    <Button variant="negative" >删除</Button>
                    <Button variant="secondary" onPress={() => dialog.dismiss()}>取消</Button>
                </Form >

            </Content>

        </Dialog >

    );
}

